//
//  PGCoreDataManager.m
//  PhotographicGuide
//
//  Created by indream on 13-2-24.
//  Copyright (c) 2013年 indream. All rights reserved.
//

//
//  UECoreDataManager.m
//  DailyMark
//
//  Created by XIN LU on 8/9/11.
//  Copyright 2011 Tencent. All rights reserved.
//

#import "PGCoreDataManager.h"

static PGCoreDataManager *_sharedInstance;

@implementation PGCoreDataManager

+ (void)initSharedInstance:(NSManagedObjectContext *)context
{
	_sharedInstance = [[PGCoreDataManager alloc] initWithManagedObjectContext:context];
}

+ (PGCoreDataManager *)sharedInstance
{
	return _sharedInstance;
}

- (id)init
{
    self = [super init];
    if (self) {
        // Initialization code here.
    }
    
    return self;
}

- (id)initWithManagedObjectContext:(NSManagedObjectContext *)context
{
	self = [super init];
	
	if (self)
	{
		_context = context;
		_error = nil;
	}
	
	return self;
}

- (NSManagedObject *)createAndAddDataByEntityName:(NSString *)entityName
{
	return [NSEntityDescription insertNewObjectForEntityForName:entityName inManagedObjectContext:_context];
}

- (NSArray *)allDataWithEntityName:(NSString *)entityName fetchLimit:(int)num
{
	return [self dataWithPredicate:nil entityName:entityName fetchLimit:num];
}

- (void)removeData:(NSManagedObject *)object
{
	[_context deleteObject:object];
}

- (void)removeDataByEntityName:(NSString *)entityName
{
	NSArray *objects = [self allDataWithEntityName:entityName fetchLimit:0];
	
	if (objects && [objects count] > 0) {
		int len = [objects count];
		for (int i=0; i<len; ++i) {
			[self removeData:(NSManagedObject *)[objects objectAtIndex:i]];
		}
	}
}

- (NSManagedObject *)dataWithUniqueIdKey:(NSString *)uniqueIdKey uniqueIdValue:(id)uniqueId entityName: (NSString *)entityName
{
	//NSPredicate *pre = [NSPredicate predicateWithFormat:@"%K == %d", uniqueIdKey, uniqueId];
	NSArray *objects = [self dataWithEntityName:entityName predicateKey:uniqueIdKey value:uniqueId];
	//[self getDataByPredicate:pre entityName:entityName fetchLimit:1];
	if (objects != nil)
	{
		return (NSManagedObject *)[objects lastObject];
	}
	
	return nil;
}

- (NSManagedObject *)dataToEditWithUniqueIdKey:(NSString *)uniqueIdKey uniqueIdValue:(id)uniqueId entityName:(NSString *)entityName
{
	NSManagedObject *obj = [self dataWithUniqueIdKey:uniqueIdKey uniqueIdValue:uniqueId entityName:entityName];
	
	if (obj != nil) {
		return obj;
	}
	
	obj = [self createAndAddDataByEntityName:entityName];
	return obj;
}

- (NSArray *)dataWithPredicate:(NSPredicate *)pre entityName:(NSString *)entityName fetchLimit:(int)num
{
	NSFetchRequest *request = [[NSFetchRequest alloc] init];
	NSEntityDescription *desc = [NSEntityDescription entityForName:entityName inManagedObjectContext:_context];
	[request setEntity:desc];
	request.predicate = pre;
    NSSortDescriptor *sortDesc = [NSSortDescriptor sortDescriptorWithKey:@"time" ascending:NO];
    [request setSortDescriptors:@[sortDesc]];
	if (num > 0) {
		request.fetchLimit = num;
	}
	
    NSError * tmp = _error;
	NSArray *objects = [_context executeFetchRequest:request error:&tmp];
	
#ifdef DEBUG
	if (_error != nil)
	{
		NSLog(@"Core Data Error: %@", _error);
        
		
		[NSException raise:@"Core Data Entity Name Error" format:nil];
		
        
	}
#endif
	return objects;
}

- (NSArray *)dataWithEntityName:(NSString *)entityName predicateKey:(NSString *)key value:(id)value
{
	NSPredicate *pre = nil;
	
	if ([value isKindOfClass:[NSString class]] || [value isKindOfClass:[NSDate class]])
	{
		pre = [NSPredicate predicateWithFormat:@"%K == %@", key, (NSString *)value];
	}
	else if ([value isKindOfClass:[NSNumber class]])
	{
		pre = [NSPredicate predicateWithFormat:@"%K == %d", key, [(NSNumber *)value intValue]];
	}
	
	NSArray *objects = [self dataWithPredicate:pre entityName:entityName fetchLimit:0];
	return objects;
}

- (NSArray *)dataWithPredicateString:(NSString *)preString entityName:(NSString *)entityName fetchLimit:(int)num
{
    NSLog(@"pre:%@",preString);
	NSPredicate *pre = [NSPredicate predicateWithFormat:preString];
	NSArray *objects = [self dataWithPredicate:pre entityName:entityName fetchLimit:num];
	return objects;
}


- (int)nextUniqueIdWithEntityName:(NSString *)entityName uniqueIdKey: (NSString *)key
{
	NSFetchRequest *request = [[NSFetchRequest alloc] init];
	NSEntityDescription *desc = [NSEntityDescription entityForName:entityName inManagedObjectContext:_context];
	[request setEntity:desc];
	NSSortDescriptor *sortDesc = [[NSSortDescriptor alloc] initWithKey:key ascending:NO];
	request.sortDescriptors = [NSArray arrayWithObject:sortDesc];
	request.fetchLimit = 1;
    NSError * tmp = _error;
	NSArray *objects = [_context executeFetchRequest:request error:&tmp];
	
	if ([objects count] == 0) {
		return 0;
	}
	
	NSManagedObject *obj = (NSManagedObject *)[objects objectAtIndex:0];
	NSNumber *maxId = (NSNumber *)[obj valueForKey:key];
	
	return [maxId intValue] + 1;
}

- (void)save
{
    NSError * tmp = _error;
	[_context save:&tmp];
}


@end

